﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Hi_Baidu.Entry.CollectionObject;
using System.Windows.Controls;
using Hi_Baidu.Packet.InPacket;
using System.Windows;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Input;
using Hi_Baidu.Timer;
using Hi_Baidu.MusicPlayer;
using Hi_Baidu.Cache.CacheObject;
using Hi_Baidu.Cache;
using Hi_Baidu.User.LogEntry;
using Hi_Baidu.Enum.User;

namespace Hi_Baidu.ProcessModel
{
    class MainBoardViewModel : Model
    {
        /// <summary>
        ///     提供好友提示面板
        /// </summary>
        public static Win_NotifyFriendInfo win_NotifyFriendInfo = new Win_NotifyFriendInfo();

        /// <summary>
        ///     新建主面板实例
        ///     如果主面板已经存在则不做任何动作
        /// </summary>
        public static void CreateInstance()
        {
            //构造主面板
            if (Globle.win_Main == null)
            {
                Globle.win_Main = new Win_Main();               
            }
        }

        /// <summary>
        ///     向主面板好友树中插入新分组
        /// </summary>
        /// <param name="item" type="Hi_Baidu.Entry.CollectionObject.Item">
        ///     <para>
        ///         新分组
        ///     </para>
        /// </param>
        public static TreeViewItem AddItem(Item item)
        {
            //创建分组
            TreeViewItem treeViewItem = new TreeViewItem();
            treeViewItem.Width = Globle.win_Main.TV_FriendList.Width;
            treeViewItem.Style = (Style)System.Windows.Application.Current.FindResource("ItemTreeView_Normal");
            treeViewItem.Margin = new Thickness(5, 5, 5, 0);
            //创建 2 x 6单元格
            Grid grid = new Grid();
            ColumnDefinition MainColumn = new ColumnDefinition();
            MainColumn.MinWidth = 50;
            grid.ColumnDefinitions.Add(MainColumn);
            grid.ColumnDefinitions.Add(new ColumnDefinition());
            grid.ColumnDefinitions.Add(new ColumnDefinition());
            grid.ColumnDefinitions.Add(new ColumnDefinition());
            grid.ColumnDefinitions.Add(new ColumnDefinition());
            grid.ColumnDefinitions.Add(new ColumnDefinition());
            grid.RowDefinitions.Add(new RowDefinition());
            grid.RowDefinitions.Add(new RowDefinition());
            TextBox txt_ModifyItem = new TextBox();
            txt_ModifyItem.MinWidth = 50;
            txt_ModifyItem.Visibility = Visibility.Collapsed;
            grid.Children.Add(txt_ModifyItem);
            Grid.SetRow(txt_ModifyItem,0);
            Grid.SetRowSpan(txt_ModifyItem, 6);
            TextBlock tb_ItemName = new TextBlock();
            tb_ItemName.MinWidth = 50;
            tb_ItemName.Text = item.Name;
            grid.Children.Add(tb_ItemName);
            Grid.SetRow(tb_ItemName, 1);
            Grid.SetColumn(tb_ItemName,0);

            TextBlock tb_LefFlag = new TextBlock();
            tb_LefFlag.Text = "  [";
            grid.Children.Add(tb_LefFlag);
            Grid.SetRow(tb_LefFlag, 1);
            Grid.SetColumn(tb_LefFlag, 1);

            TextBlock tb_ItemOnlineCount = new TextBlock();
            tb_ItemOnlineCount.Text = "0";
            grid.Children.Add(tb_ItemOnlineCount);
            Grid.SetRow(tb_ItemOnlineCount, 1);
            Grid.SetColumn(tb_ItemOnlineCount, 2);

            TextBlock tb_CenterFlag= new TextBlock();
            tb_CenterFlag.Text = "/";
            grid.Children.Add(tb_CenterFlag);
            Grid.SetRow(tb_CenterFlag, 1);
            Grid.SetColumn(tb_CenterFlag, 3);

            TextBlock tb_ItemTotalCount = new TextBlock();
            tb_ItemTotalCount.Text = "0";
            grid.Children.Add(tb_ItemTotalCount);
            Grid.SetRow(tb_ItemTotalCount, 1);
            Grid.SetColumn(tb_ItemTotalCount, 4);

            TextBlock tb_RightFlag = new TextBlock();
            tb_RightFlag.Text = "]";
            grid.Children.Add(tb_RightFlag);
            Grid.SetRow(tb_RightFlag, 1);
            Grid.SetColumn(tb_RightFlag, 5);
            treeViewItem.Header = grid;
            treeViewItem.Tag = item;
            Globle.win_Main.TV_FriendList.Items.Add(treeViewItem);
            return treeViewItem;
        }

        /// <summary>
        ///     向主面板好友树中的指定分组下加入好友
        /// </summary>
        /// <param name="ItemId" type="string">
        ///     <para>
        ///         分组ID
        ///     </para>
        /// </param>
        /// <param name="friend" type="Hi_Baidu.Entry.CollectionObject.Friend">
        ///     <para>
        ///         新好友
        ///     </para>
        /// </param>
        public static void AddFriend(String ItemId, Friend friend)
        {
            AddFriend((Item)Globle.itemCollection.GetMemberByKey(ItemId), friend);
        }

        /// <summary>
        ///     向主面板好友树中的指定分组下加入好友
        /// </summary>
        /// <param name="item" type="Hi_Baidu.Entry.CollectionObject.Item">
        ///     <para>
        ///         指定分组
        ///     </para>
        /// </param>
        /// <param name="friend" type="Hi_Baidu.Entry.CollectionObject.Friend">
        ///     <para>
        ///         新好友
        ///     </para>
        /// </param>
        public static void AddFriend(Item item, Friend friend)
        {
            foreach (TreeViewItem treeviewitem in Globle.win_Main.TV_FriendList.Items)
            {
               if (treeviewitem.Tag is Item)
               {
                    if ((treeviewitem.Tag as Item).Key == item.Key)
                    {
                        TreeViewItem treeViewItem = new TreeViewItem();
                        treeViewItem.Margin = new System.Windows.Thickness(0, 3, 3, 0);
                        treeViewItem.MouseEnter += new System.Windows.Input.MouseEventHandler(treeViewItem_MouseEnter);
                        treeViewItem.MouseLeave += new System.Windows.Input.MouseEventHandler(treeViewItem_MouseLeave);
                            //////////////////////////////////////////////////////////////////
                            ///        开始创建好友树节点模板
                            //////////////////////////////////////////////////////////////////
                            //新建表格布局，2行2列
                            Grid grid = new Grid();
                            grid.Margin = new Thickness(0, 2, 5, 2);
                            grid.RowDefinitions.Add(new RowDefinition());
                            grid.RowDefinitions.Add(new RowDefinition());
                            grid.ColumnDefinitions.Add(new ColumnDefinition());
                            grid.ColumnDefinitions.Add(new ColumnDefinition());
                            //打入默认头像 + 外围边框
                            Image headImage = new Image();
                            headImage.Source = new BitmapImage(new Uri("pack://application:,,,/syshead/2a88fcf8c64ad43a97dc417b41e524cc_m.jpg"));
                            friend.HeadImage = headImage;
                            Border border = new Border();
                            border.BorderBrush = Brushes.LightGray;
                            border.Child = headImage;
                            border.BorderThickness = new Thickness(1);
                            grid.Children.Add(border);
                            Grid.SetRow(border,0);
                            Grid.SetColumn(border,0);
                            Grid.SetRowSpan(border,2);
                            //打入昵称
                            TextBlock tb_NickName = new TextBlock();
                            tb_NickName.Margin = new Thickness(5,0,5,1);
                            tb_NickName.Text = friend.Username;
                            tb_NickName.HorizontalAlignment = HorizontalAlignment.Left;
                            tb_NickName.VerticalAlignment = VerticalAlignment.Center;
                            grid.Children.Add(tb_NickName);
                            Grid.SetRow(tb_NickName,0);
                            Grid.SetColumn(tb_NickName,1);
                            //打入个性签名
                            TextBlock tb_Prod = new TextBlock();
                            tb_Prod.Margin = new Thickness(5, 0, 5, 0);
                            tb_Prod.Foreground = Brushes.LightGray;
                            tb_Prod.Text = "(无)";
                            tb_Prod.HorizontalAlignment = HorizontalAlignment.Left;
                            tb_Prod.VerticalAlignment = VerticalAlignment.Center;
                            grid.Children.Add(tb_Prod);
                            Grid.SetRow(tb_Prod, 1);
                            Grid.SetColumn(tb_Prod, 1);
                            treeViewItem.Header = grid;
                        treeViewItem.Tag = friend;
                        treeviewitem.Items.Add(treeViewItem);
                        friend.VisualTreeItem = treeviewitem;
                        friend.FriendNode = treeViewItem;
                    }
               }
            }
        }

        static void treeViewItem_MouseLeave(object sender, System.Windows.Input.MouseEventArgs e)
        {
            Point WP = ((sender as TreeViewItem).Header as Grid).PointFromScreen(new Point(0, 0));

            Border TreeViewImageBorder = (Border)(((sender as TreeViewItem).Header as Grid).Children[0]);
            TreeViewImageBorder.BorderBrush = Brushes.LightGray;
            int X = System.Windows.Forms.Control.MousePosition.X;
            if (!(X> WP.X && X < WP.X + win_NotifyFriendInfo.Width))
            {
                win_NotifyFriendInfo.Hide();
            }
        }

        static void treeViewItem_MouseEnter(object sender, System.Windows.Input.MouseEventArgs e)
        {
            Border TreeViewImageBorder = (Border)(((sender as TreeViewItem).Header as Grid).Children[0]);
            TreeViewImageBorder.BorderBrush = Brushes.Green;
            win_NotifyFriendInfo.TB_NickName.Text = ((TextBlock)(((sender as TreeViewItem).Header as Grid).Children[1])).Text;
            win_NotifyFriendInfo.TB_NickName.Foreground = ((TextBlock)(((sender as TreeViewItem).Header as Grid).Children[1])).Foreground;
            win_NotifyFriendInfo.TB_Prod.Text = ((TextBlock)(((sender as TreeViewItem).Header as Grid).Children[2])).Text;
            Point WP = ((sender as TreeViewItem).Header as Grid).PointToScreen(new Point(0, 0));
            win_NotifyFriendInfo.Left = WP.X - win_NotifyFriendInfo.Width;
            win_NotifyFriendInfo.Top = WP.Y;
            win_NotifyFriendInfo.Show();
        }

        public static void UpdateFriend(GetFriendInfoReplyPacket inpackage)
        {
            String Friend_Username = inpackage.GetInfoByKey("USERNAME");
            if (Friend_Username != null)
            {
                Friend Ffriend = ((Friend)Globle.friendCollection.GetMemberByKey(Friend_Username));
                Item item = Ffriend.ForItem;
                foreach (TreeViewItem treeViewItem in Globle.win_Main.TV_FriendList.Items)
                {
                    //找到用户所在分组
                    if (treeViewItem.Tag is Item)
                    {
                        //遍历用户所在分组
                        if ((treeViewItem.Tag as Item).Key == item.Key)
                        {
                            var friend = from TreeViewItem TempFriend in treeViewItem.Items where (TempFriend.Tag as Friend).Username == inpackage.GetInfoByKey("USERNAME") select TempFriend;
                            foreach (var fd in friend)
                            {
                                TreeViewItem TVI = (TreeViewItem)fd;
                                Grid grid =  (Grid)TVI.Header;
                                TYPE_UserMark userMark = Globle.userMarkManager.GetMemberByKey(((TextBlock)grid.Children[1]).Text) as TYPE_UserMark;
                                if (userMark != null)
                                {
                                    ((TextBlock)grid.Children[1]).Text = userMark.MarkName;
                                }
                                else
                                {
                                    ((TextBlock)grid.Children[1]).Text = inpackage.GetInfoByKey("NICKNAME");
                                }
                                if ((User.Level.MessionLevel)int.Parse(inpackage.GetInfoByKey("MESSION")) == Hi_Baidu.User.Level.MessionLevel.VIP)
                                {
                                    ((TextBlock)grid.Children[1]).Foreground = Brushes.Red;
                                }
                                ((TextBlock)grid.Children[2]).Text = "(" + inpackage.GetInfoByKey("PROD") + ")";

                                //更新用户头像
                                Image headImage = new Image();
                                headImage.Height = 32;
                                headImage.Width = 32;
                                //好友在线
                                if (inpackage.GetFriendLoginLive())
                                {
                                    headImage.Source = new BitmapImage(new Uri("pack://application:,,,/syshead/" + inpackage.GetInfoByKey("HEADIMAGE") + "_m.jpg"));
                                    FriendTreeViewModel.AddOnlineCountForItem(Ffriend);
                                }
                                //好友离线
                                else
                                {
                                    FormatConvertedBitmap formatCpmvertedBitmap = new FormatConvertedBitmap();
                                    formatCpmvertedBitmap.BeginInit();
                                    formatCpmvertedBitmap.Source = new BitmapImage(new Uri("pack://application:,,,/syshead/" + inpackage.GetInfoByKey("HEADIMAGE") + "_m.jpg"));
                                    formatCpmvertedBitmap.DestinationFormat = PixelFormats.Gray32Float;
                                    formatCpmvertedBitmap.EndInit();
                                    headImage.Source = formatCpmvertedBitmap;
                                }
                                FriendTreeViewModel.AddTotalCountForItem(Ffriend);
                                ((Border)grid.Children[0]).Child = headImage;
                            }
                        }
                    }
                }
                //更新该好友的本地资料
                Friend FD = (Friend)Globle.friendCollection.GetMemberByKey(Friend_Username);
                if (FD != null)
                {
                    FD.OnlineState    = inpackage.GetFriendLoginLive();
                    FD.Name            = inpackage.GetInfoByKey("NICKNAME");
                    FD.Mession =      (Hi_Baidu.User.Level.MessionLevel)int.Parse(inpackage.GetInfoByKey("MESSION"));
                    FD.Infomation     = inpackage.GetInfoByKey("MARK");
                    FD.Age               = int.Parse(inpackage.GetInfoByKey("AGE"));
                    FD.Prod              = inpackage.GetInfoByKey("PROD");
                    FD.HeadImageName = inpackage.GetInfoByKey("HEADIMAGE");
                    FD.IpAddress = inpackage.GetInfoByKey("IPADDRESS");
                    FD.TalkPort = int.Parse(inpackage.GetInfoByKey("TALKPORT"));
                    FD.VideoPort = int.Parse(inpackage.GetInfoByKey("VIDEOPORT"));
                    FD.VoicePort = int.Parse(inpackage.GetInfoByKey("VOICEPORT"));
                    FD.FilePort = int.Parse(inpackage.GetInfoByKey("FILEPORT"));
                }
            }
        }

        /// <summary>
        ///     刷新自身信息在主面板上
        /// </summary>
        public static void FlushMyInfo()
        {
            if(Globle.user.DIC_USERINFO != null && Globle.win_Main != null)
            {
                String LoginLiveText = "";
                switch ((Hi_Baidu.Packet.InPacket.LoginReplyPacket.LoginState)BitConverter.ToInt32(Globle.user.DIC_USERINFO["LOGINLIVE"],0))
                {
                    case Hi_Baidu.Packet.InPacket.LoginReplyPacket.LoginState.Normal:
                        ((ComboBoxItem) Globle.win_Main.cb_OnlineState.Items[0]).IsSelected = true;
                        break;
                    case Hi_Baidu.Packet.InPacket.LoginReplyPacket.LoginState.Hidden:
                        ((ComboBoxItem)Globle.win_Main.cb_OnlineState.Items[1]).IsSelected = true;
                        break;
                    case Hi_Baidu.Packet.InPacket.LoginReplyPacket.LoginState.Busy:
                        ((ComboBoxItem)Globle.win_Main.cb_OnlineState.Items[2]).IsSelected = true;
                        break;
                    case Hi_Baidu.Packet.InPacket.LoginReplyPacket.LoginState.Away:
                        ((ComboBoxItem)Globle.win_Main.cb_OnlineState.Items[3]).IsSelected = true;
                        break;
                }
                Globle.win_Main.cb_OnlineState.SelectionChanged += new SelectionChangedEventHandler(cb_OnlineState_SelectionChanged);
                Globle.win_Main.tb_Username.Text = Encoding.Default.GetString(Globle.user.DIC_USERINFO["NICKNAME"]);// +LoginLiveText;
                Globle.win_Main.tb_UserProd.Text = Encoding.Default.GetString(Globle.user.DIC_USERINFO["PROD"]);
                Globle.win_Main.Img_UserHead.Source = new BitmapImage(new Uri("pack://application:,,,/syshead/" + Encoding.Default.GetString(Globle.user.DIC_USERINFO["HEADIMAGE"]) + "_l.jpg"));
            }
        }

        static void cb_OnlineState_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            //用户更改了上线状态
            if (((e.Source as ComboBox).SelectedItem as ComboBoxItem).Tag.ToString() != Encoding.Default.GetString(Globle.user.DIC_USERINFO["LOGINLIVE"]))
            {
                ONLIN_STATE OnlineState = (ONLIN_STATE)int.Parse(((e.Source as ComboBox).SelectedItem as ComboBoxItem).Tag.ToString());
                Globle.user.USER_ONLINE_STATE = OnlineState;
                cls_Application_Init.SetNoityIconByUserState(OnlineState);
                //提交修改用户状态请求
                UserProcessModel.ChanageUserOnlineState(Globle.user.DIC_USERINFO["USERNAME"],
                                                        BitConverter.GetBytes((int)OnlineState));
                //创建超时器
                ChanageUserOnlineState_TimeOutEvent chanageUserOnlineState_TimeOutEvent =
                    new ChanageUserOnlineState_TimeOutEvent(Globle.user.DIC_USERINFO["USERNAME"], BitConverter.GetBytes((int)OnlineState),
                        "ChanageUserOnlineStateTimeOut", 2000, 2);
                //安装超时器
                Globle.timeoutTimerManager.InstallTimer(chanageUserOnlineState_TimeOutEvent);
            }
        }

        /// <summary>
        ///     更新自身个性签名
        /// </summary>
        public static void UpdateMyProd()
        {
            Globle.win_Main.tb_UserProd.Text = Globle.win_Main.txt_NotifyNickName.Text;
        }

        /// <summary>
        ///     更新指定好友的在线状态为上线
        /// </summary>
        /// <param name="friend">好友对象</param>
        public static void ChanageFriendOnlineState(Friend friend)
        {
            if(!friend.OnlineState)
            {
                friend.OnlineState = true;
                Grid grid = friend.FriendNode.Header as Grid;
                Border border = grid.Children[0] as Border;
                Image img = border.Child as Image;
                img.Source = new BitmapImage(new Uri("pack://application:,,,/syshead/" + friend.HeadImageName + "_m.jpg"));
                FriendTreeViewModel.AddOnlineCountForItem(friend);
                MusicPlayer.MusicPlayer.Play(Hi_Baidu.MusicPlayer.MusicPlayer.SongType.ONLINE);
                Win_TalkWindow win_TalkWindow = Globle.popWindowManager.GetMemberByKey(friend.Username) as Win_TalkWindow;
                //更换当前聊天窗口的上线状态
                if (win_TalkWindow != null)
                {
                    win_TalkWindow.Img_OnlineState.Source = win_TalkWindow.BI_Online;
                }
            }
        }

        /// <summary>
        ///     删除好友
        /// </summary>
        public static void DeleteFriend()
        {
            TreeViewItem treeViewItem = Globle.win_Main.TV_FriendList.SelectedItem as TreeViewItem;
            if (treeViewItem != null && treeViewItem.Tag is Friend)
            {
                Friend friend = treeViewItem.Tag as Friend;
                //创建删除好友缓存
                DeleteFriendCache deleteFriendCache = new DeleteFriendCache("DeleteFriend:" + friend.Key, friend.Username, friend.ForItem.Key, DateTime.MaxValue);
                //将好友缓存打入缓存集合
                if (DeclareCacheManager.friendControlCacheManager.AddFriendCache(deleteFriendCache))
                {
                    //向服务器发送删除好友请求
                    FriendProcessModel.DeleteFriend(Globle.user.DIC_USERINFO["USERNAME"], Encoding.Default.GetBytes(friend.Username), BitConverter.GetBytes(int.Parse(friend.ForItem.Key)));
                }
            }   
        }

        /// <summary>
        ///     从好友数中删除指定好友节点
        /// </summary>
        /// <param name="inpackage"></param>
        public static void DeleteFriend(DeleteFriendReplyPacket inpackage)
        {
            Friend friend = Globle.friendCollection.GetMemberByKey(inpackage.GetFriendName()) as Friend;
            TreeViewItem treeViewItem = friend.VisualTreeItem;
            treeViewItem.Items.Remove(friend.FriendNode);
            //更改分组计数设置
            FriendTreeViewModel.ReduceOnlineCountForItem(friend);
            FriendTreeViewModel.ReduceTotalCountForItem(friend.VisualTreeItem);
            //从分组集合中移除该分组
            Globle.friendCollection.Remove(inpackage.GetFriendName());
        }

        public static void Show()
        {
            Globle.win_Login.Hide();
            Globle.win_Main.Show();
        }
    }
}
